package com.podcstr.dao;

import com.podcstr.entity.User;
import org.apache.log4j.Logger;

import javax.persistence.NoResultException;
import java.util.Date;

/**
 * @author azim
 * @since 5/12/13 
 */

public class UserDaoImpl extends GenericDaoImpl<User, Long> implements UserDao {

    private final Logger log = Logger.getLogger(UserDaoImpl.class);

    @Override
    public void toggleDisable(long userId) {

        User user = getEntityManager().find(User.class, userId);

        if (user.isActive() == true) {
            user.setActive(false);
        } else {
            user.setActive(true);
        }
        getEntityManager().merge(user);

        log.info(new Date() + " : User with id : " + userId + " has now active value of " + user.isActive() + ".");
    }

    @Override
    public User findUserByUsername(String username) {

        User user = null;

        try {

            user = (User) (getEntityManager().createNamedQuery("tb_users.findByUserName").setParameter("username", username).getSingleResult());
        } catch (NoResultException noe) {

            user = null;
        }


        if (user != null) {
            log.info(new Date() + " : Returning user with username : " + username);
        }
        return user;
    }
}
